package com.sure.supermarketserver.branch.information.impl;

import com.sure.supermarketserver.branch.information.BranchDto;
import com.sure.supermarketserver.branch.information.BranchService;
import com.sure.supermarketserver.branch.information.StaffDto;
import com.sure.supermarketserver.branch.information.dao.BranchDao;
import com.sure.supermarketserver.common.Utils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

@Service//说明这是一个受spring容器管理的业务组件(Bean)
@Transactional//本类方法均为事务性的
public class BranchServiceImpl implements BranchService {

    @Resource
    private BranchDao branchDao;

    @Override
    public Map<String, Object> getBranchList(BranchDto dto) {
        return Utils.getPage(dto, () -> branchDao.findBranchList(dto));
    }

    @Override
    public void addBranch(BranchDto dto) {
        dto.setBr_time(new Date());
        try {
            boolean hasbranch = branchDao.findBranch(dto.getBr_id());
            if (hasbranch) {
                throw new RuntimeException("该分店已存在，编号被占用！");
            }
            branchDao.insertBranch(dto);
        } catch (Exception e) {
            if (e instanceof RuntimeException) {
                throw e;
            }
            throw new RuntimeException("添加分店失败！", e);
        }
    }

    @Override
    public void delBranch(String id) {
        try {
            branchDao.delBranch(id);
        } catch (Exception e) {
            throw new RuntimeException("删除分店失败，仍存在员工或商品未处理！", e);
        }
    }

    @Override
    public void updBranch(BranchDto dto) {
        branchDao.updBranch(dto);
    }

    @Override
    public Map<String, Object> getBrst(StaffDto dto) {
        return Utils.getPage(dto, () -> branchDao.findBrst(dto));
    }
}
